package cn.wolfcode.aspect;

import cn.wolfcode.domain.OperateLog;
import cn.wolfcode.mapper.OperateLogMapper;
import cn.wolfcode.util.JwtUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
@Component
@Aspect
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;
    @Around("@annotation(cn.wolfcode.aspect.Mylog)")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        String token = request.getHeader("token");
        String username = (String) JwtUtils.parseJwt(token).get("username");
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUser(username);
        operateLog.setOperateTime(new Date());
        operateLog.setClassName(pjp.getTarget().getClass().getName());

        operateLog.setMethodName(pjp.getSignature().getName());
        operateLog.setArgs(Arrays.toString(pjp.getArgs()));
        long startTime = System.currentTimeMillis();
        Object proceed=pjp.proceed();
        long endTime = System.currentTimeMillis();
        operateLog.setReturnValue(JSON.toJSONString(proceed));

        operateLog.setCostTime((int) (endTime-startTime));
        operateLogMapper.add(operateLog);
        return proceed;
    }
}
